import { useEffect, useRef, useState } from 'react';

type SizeType = {
  width: number;
  height: number;
};

export default function usePlaygroundSize() {
  const [size, setSize] = useState<SizeType>({ width: 0, height: 0 });
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const observer = new ResizeObserver(() => {
      if (!ref.current) {
        return;
      }
      const style = window.getComputedStyle(ref.current);
      setSize({ width: parseInt(style.width, 10), height: parseInt(style.height, 10) });
    });

    if (ref.current) {
      observer.observe(ref.current);
    }
    return () => {
      observer.disconnect();
    };
  }, []);

  return [ref, size] as const;
}
